<template>
  <div class="regist">
    <el-row>
      <el-col :offset="8" :span="8">
        <div class="regist-logo">
          <img src="../../../public/images/avatar.png" alt="" />
        </div>
        <el-card class="box-card" shadow="always">
          <div class="regist-title">
            <h2>注册</h2>
          </div>
          <el-form
            ref="registForm"
            :model="registForm"
            :rules="registFormRules"
            class="login-form"
            autocomplete="on"
            label-position="right"
            label-width="100px"
          >
            <el-form-item label="邮箱" prop="email">
              <el-col :span="20">
                <el-input
                  prefix-icon="el-icon-message"
                  ref="inputEmail"
                  v-model="registForm.email"
                  placeholder="请输入邮箱"
                  name="email"
                  type="email"
                  tabindex="1"
                  autocomplete="on"
                />
              </el-col>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-col :span="20">
                <el-input
                  prefix-icon="el-icon-user"
                  ref="inputUser"
                  v-model="registForm.username"
                  placeholder="请输入用户名"
                  name="username"
                  type="text"
                  tabindex="1"
                  autocomplete="on"
                />
              </el-col>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-col :span="20">
                <el-input
                  prefix-icon="el-icon-lock"
                  ref="inputpwd"
                  v-model="registForm.password"
                  placeholder="请输入密码"
                  name="password"
                  type="password"
                  tabindex="1"
                  autocomplete="on"
                />
              </el-col>
            </el-form-item>
            <el-form-item label="电话号" prop="phone">
              <el-col :span="20">
                <el-input
                  prefix-icon="el-icon-phone-outline"
                  ref="phone"
                  v-model="registForm.phone"
                  placeholder="请输入电话号"
                  name="phone"
                  type="tel"
                  tabindex="1"
                  autocomplete="on"
                >
                  <el-button
                    :disabled="ableCodeBtn"
                    @click="getAuthCode('registForm')"
                    slot="append"
                    >{{ codeBtnContent }}</el-button
                  >
                </el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="验证码" prop="authcode">
              <el-col :span="20">
                <el-input
                  prefix-icon="el-icon-key"
                  ref="authcode"
                  v-model="registForm.authcode"
                  placeholder="请输入验证码"
                  name="authcode"
                  type="tel"
                  tabindex="1"
                  autocomplete="on"
                />
              </el-col>
            </el-form-item>
            <el-form-item align="center">
              <el-col :span="18">
                <el-button type="primary" @click="submitForm('registForm')"
                  >提交</el-button
                >
                <el-button @click="resetForm('registForm')">重置</el-button>
              </el-col>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { qrcodeWxRegist, sendSms, validSmsCode } from "@/api/wx";
import { validEmail, validPwd, validPhone, randomNum } from "@/utils/validate";
import { Message } from "element-ui";
import { mapActions, mapGetters } from "vuex";
export default {
  data() {
    var validateEmail = (rule, value, callback) => {
      if (validEmail(value)) {
        return callback();
      }
      callback(new Error("请输入有效邮箱"));
    };
    var validatePwd = (rule, value, callback) => {
      if (validPwd(value)) {
        return callback();
      }
      callback(new Error("至少1个大写字母，1个小写字母和1个数字"));
    };
    var validatePhone = (rule, value, callback) => {
      if (validPhone(value)) {
        return callback();
      }
      callback(new Error("请输入有效电话号"));
    };
    var validateCode = (rule, value, callback) => {
      if (this.code === Number(value)) {
        return callback();
      }
      callback(new Error("验证码无效"));
    };
    return {
      openid: "",
      access_token: "",
      registForm: {},
      registFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" }
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 4,
            max: 30,
            message: "长度在 4 到 30 个字符",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 8,
            max: 16,
            message: "长度在 8 到 16 个字符",
            trigger: "blur"
          },
          { validator: validatePwd, trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入电话号", trigger: "blur" },
          { min: 11, max: 11, message: "长度在 11 个字符", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" }
        ],
        authcode: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      ableCodeBtn: false,
      timer: null,
      seconds: 30,
      sendSmsParams: {
        PhoneNumbers: "",
        SignName: "优创智投",
        TemplateCode: "SMS_133025080",
        TemplateParam: "",
        event: "regist"
      },
      code: null
    };
  },
  computed: {
    ...mapGetters(["wechatAccount"]),
    codeBtnContent() {
      if (this.ableCodeBtn) {
        return `剩余${this.seconds}秒`;
      } else {
        return "获取验证码";
      }
    }
  },
  watch: {
    // ↓ 监听地址栏 解构出 重定向 参数 和 其他参数 ↓
    $route: {
      handler: function(route) {
        for (const key in route.params) {
          if (key === "openid") {
            this.openid = route.params[key];
          }
          if (key === "access_token") {
            this.access_token = route.params[key];
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    ...mapActions({
      setWechatAccount: "user/setWechatAccount"
    }),
    /**
     * @function VueMethods
     * @description 校验注册表单设置执行 sendSms() 并设置 30s真空期
     * @param {String} formName 表单Ref值
     * @returns void
     */
    getAuthCode(formName) {
      this.$refs[formName].validateField("phone", err => {
        if (!err) {
          this.sendSms();
          this.ableCodeBtn = true;
          this.timer = setInterval(() => {
            if (this.seconds <= 0) {
              clearTimeout(this.timer);
              this.ableCodeBtn = false;
              this.seconds = 30;
            } else {
              this.seconds--;
            }
          }, 1000);
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let bool = await this.validSmsCode();
          if (bool) {
            this.regist();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 发送短信
    async sendSms() {
      this.sendSmsParams.PhoneNumbers = this.registForm.phone;
      this.code = randomNum();
      this.sendSmsParams.TemplateParam = JSON.stringify({ code: this.code });
      let res = await sendSms(this.sendSmsParams);
      if (res.code === 200) {
        Message.success({
          message: "短信已发送，注意留意手机。"
        });
      }
    },
    // 注册
    async regist() {
      let _data = {
        username: "",
        password: "",
        email: ""
      };
      for (const key in _data) {
        _data[key] = this.registForm[key];
      }
      let data = Object.assign(_data, {
        openid: this.openid,
        access_token: this.access_token
      });
      let res = await qrcodeWxRegist(data);
      if (res.code === 10000) {
        let { username, email, id } = res.data;
        let accounts = JSON.parse(this.wechatAccount);
        let index = 0;
        Object.keys(accounts).forEach(item => {
          let _index = item - 0;
          if (_index > index) {
            index = _index;
          }
        });
        accounts[index + 1] = { username, email, id };
        this.setWechatAccount(JSON.stringify(accounts));
        this.$nextTick(() => {
          this.$router.back(-1);
        });
      }
    },
    async validSmsCode() {
      let res = await validSmsCode({
        captcha: this.registForm.authcode,
        mobile: this.registForm.phone,
        event: "regist"
      });
      if (res.hasOwnProperty("data") && res.data[0] === "ok") return true;
      return false;
    }
  }
};
</script>
<style lang="scss" scoped>
.regist {
  height: 100%;
  background: url("../../../public/images/gs.png");
  background: linear-gradient(rgba(196, 102, 0, 0.2), rgba(155, 89, 182, 0.2)),
    url("../../../public/images/gs.png");
  &-logo {
    text-align: center;
  }
  &-title {
    text-align: center;
    letter-spacing: 50px;
    padding-left: 50px;
  }
}
</style>
